package com.open.capacity.db.service.impl;

import com.alibaba.fastjson.JSON;
import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.model.DBTable;
import com.open.capacity.common.model.TableField;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.db.dao.FieldMapper;
import com.open.capacity.db.feign.FireBirdFeignClient;
import com.open.capacity.db.service.FieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class FieldServiceImpl implements FieldService {

    @Autowired(required = false)
    FieldMapper fieldMapper;
    @Autowired
    FireBirdFeignClient fireBirdFeignClient;

    @Override
    public PageResult getTableFieldList(Map map) {
        try {
            Integer page = Integer.valueOf((String) map.get("page")) - 1;
            Integer limit = Integer.valueOf((String) map.get("limit"));
            DBTable dbTable = JSON.parseObject((String) map.get("dbTable"), DBTable.class);
            PageUtil.pageParamConver(map, true);
            map.put("page", page*limit);
            map.put("limit", limit);
            map.put("tableId", dbTable.getTableId());
            long count = fieldMapper.getTableFieldListCount(map);
            List<TableField> list = Collections.emptyList();
            if (count > 0) {
                list = fieldMapper.getTableFieldList(map);
            } else {
                List<TableField> fields = fireBirdFeignClient.getTableFields(map);
                if (fields == null)
                    return PageResult.<TableField>builder().data(null).code(1).count(count).build();
                List<TableField> collect = fields.stream()
                        .map(field -> {
                            field.setTableId(dbTable.getTableId());
                            return field;
                        }).collect(Collectors.toList());
                fieldMapper.saveTableFields(collect);
                list = fieldMapper.getTableFieldList(map);
            }
            return PageResult.<TableField>builder().data(list).code(0).count(count).build();
        } catch (ServiceException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }
}
